import es
from popuplib import create as popup

current = 0

class Vote(object):
    def __init__(self, name):
        self.name = name
        self.vote = self.submitted = self.question = 0
        self.options = {}
    def create(self, question='', options=()):
        self.question = question # Needed for printVote() to display the question
        if self.vote:
            self.delete()
        self.vote = popup('vote_%s' % self.name)
        self.vote.addline('Vote: ' + question)
        self.vote.addline(' ')
        self.vote.addline('-------------------')
        i = 0
        for option in options:
            i += 1
            self.vote.addline('->%s. %s' % (i, option))
            self.options[i] = option
        self.vote.addline('-------------------')
        # self.vote.addline(' ') # Looks better without in my honest opinion
        self.vote.addline('0. Close')
        self.vote.menuselect = self.submit
    def delete(self):
        self.vote.delete()
        self.options.clear()
    def start(self):
        for userid in es.getUseridList():
            self.vote.send(userid)
    def printVote(self):
        options = []
        for option in self.options:
            options.append(self.options[option])
        return 'Votename: %s, Question: %s, Options: %s' % (self.name, self.question, options)
    def submit(self, userid, choice, popupname):
        if choice != 10:
            choice = self.options[choice]
            es.tell(userid, '#multi', '#green[#lightgreenAbsoluteAdmin#green] #defaultYou selected #green%s #defaultfrom #lightgreen%s' % (choice, popupname.replace('vote_', '')))
            self.submitted += 1
            if self.submitted == es.getplayercount():
                es.msg('#multi', '#green[#lightgreenAbsoluteAdmin#green] #defaultOption #green%s #defaultwon!' % choice)
                self.delete()

def formatText(text):
    text = text.replace('"', '\n').replace(' ', '').split('\n')
    for x in text:
        if x == '':
            text.remove(x)
    return text

def init(name):
    global current
    current = name
    return Vote(name)

def create(question, options):
    Vote(current).create(question, options)

def start():
    Vote(current).start()

def delete(name):
    Vote(name).delete()

def printVote(name):
    Vote(name).printVote()
